<template>
  <div class="data-list">
    <data-load-more-list :dataSource="dataSource" :loading="loadingData" @loadData="loadDataList">
      <template #default="{ data }">
        <video-item :data="data"></video-item>
      </template>
    </data-load-more-list>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, withDefaults } from 'vue'
import { loadVideoListHttpRequest, type VideoInfoPaginationResponse } from '@/services/api/home'
import { useRoute } from 'vue-router'
import { useCategoryStore } from '@/stores/category'

const route = useRoute()
const dataSource = ref<VideoInfoPaginationResponse>({
  totalCount: 0,
  pageSize: 0,
  pageNo: 0,
  pageTotal: 0,
  list: []
})
const loadingData = ref(false)

const loadDataList = async () => {
  const params = {
    pageNo: dataSource.value?.pageNo || ''
  }
  Object.assign(params, categoryIdInfo.value)
  loadingData.value = true
  const res = await loadVideoListHttpRequest(params)
  loadingData.value = false
  const dataList = dataSource.value?.list
  dataSource.value = Object.assign({}, res.data)
  if (res.data.pageNo > 1) {
    dataSource.value.list = dataList!.concat(res.data.list)
  }
}

const initData = () => {
  convertCodeToId(route.params.pCategoryCode, route.params.categoryCode)
  loadDataList()
}

const categoryStore = useCategoryStore()
const categoryInit = ref(false)
const categoryIdInfo = ref<any>({})

const categoryMap = categoryStore.categoryMap
const convertCodeToId = (pCategoryCode: any, categoryCode: any) => {
  let pCategoryId = ''
  let categoryId = ''
  if (pCategoryCode) {
    pCategoryId = categoryMap[pCategoryCode] ? categoryMap[pCategoryCode].categoryId : ''
  }
  if (categoryCode) {
    categoryId = categoryMap[categoryCode] ? categoryMap[categoryCode].categoryId : ''
  }
  categoryIdInfo.value = {
    pCategoryId,
    categoryId
  }
}

watch(
  () => route.params,
  (newVal, oldVal) => {
    if (newVal) {
      // 如果分类数据未初始化，则跳过
      if (!categoryInit.value) return
      // 保存当前父分类代码到Store
      categoryStore.saveCurrentPCategory(route.params.pCategoryCode)
      // 初始化/刷新数据
      initData()
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => categoryStore.categoryMap,
  (newVal, oldVal) => {
    // 如果分类数据为空则跳过
    if (!newVal || Object.keys(newVal).length == 0) {
      return
    }
    // 标记分类数据已初始化 防止上面的监听又加载一边数据
    categoryInit.value = true
    // 保存当前父分类代码到Store
    categoryStore.saveCurrentPCategory(route.params.pCategoryCode)
    initData()
  },
  { immediate: true, deep: true }
)
</script>

<style lang="less" scoped></style>
